package datastructure;

/**
 * 顺序栈
 *
 * @param <E> 栈中所存元素类型
 */
public class SqStackClass<E> {
    private E[] data;
    private int top;
    private final static int INIT_CAPACITY = 10;

    public SqStackClass() {
        data = (E[]) new Object[INIT_CAPACITY];
        top = 0;
    }

    @Override
    public String toString() {
        StringBuffer stringBuffer = new StringBuffer("[" + (top > 0 ? data[0] : ""));
        for (int i = 1; i < top; i++)
            stringBuffer.append(" -> " + data[i]);
        stringBuffer.append("]");
        return stringBuffer.toString();
    }

    private void updateCapacity(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < top; i++)
            newData[i] = data[i];
        data = newData;
    }

    public boolean empty() {
        return top == 0;
    }

    public void push(E e) {
        if (top >= data.length)
            updateCapacity(2 * top);
        data[top++] = e;
    }

    public E pop() {
        if (empty())
            throw new IllegalArgumentException("栈空！");
        E e = data[top - 1];
        data[--top] = null;
        if (data.length > INIT_CAPACITY && data.length / 4 >= top)
            updateCapacity(data.length / 2);
        return e;
    }

    public E peek() {
        if (empty())
            throw new IllegalArgumentException("栈空！");
        return data[top - 1];
    }
}
